<template>
  <div class="module-detail" v-loading="loading">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ name: 'Modules' }">模块列表</el-breadcrumb-item>
          <el-breadcrumb-item>{{ module.name || '模块详情' }}</el-breadcrumb-item>
        </el-breadcrumb>
        <h1 class="page-title">{{ module.name || '模块详情' }}</h1>
      </div>
      <div class="header-actions">
        <el-button @click="goBack" :icon="ArrowLeft">返回列表</el-button>
        <el-button type="primary" :icon="Download" @click="exportDetail" :disabled="loading">
          导出详情
        </el-button>
      </div>
    </div>

    <!-- 错误提示 -->
    <el-alert
      v-if="error"
      :title="error"
      type="error"
      show-icon
      :closable="false"
      class="error-alert"
    />

    <!-- 模块详情内容 -->
    <div v-if="!loading && !error && module.id">
      <!-- 基本信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><InfoFilled /></el-icon>
            <span>基本信息</span>
          </div>
        </template>

        <el-row :gutter="24">
          <el-col :span="8">
            <div class="info-item">
              <label>模块ID</label>
              <span class="value">{{ module.id }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>模块名称</label>
              <span class="value">{{ module.name }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>文件类型</label>
              <span class="value">{{ module.type }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="24" style="margin-top: 16px;">
          <el-col :span="8">
            <div class="info-item">
              <label>子系统</label>
              <span class="value">{{ module.subsystem }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>组件</label>
              <span class="value">{{ module.componentName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>模块分组</label>
              <el-tag :type="getModGroupTagType(module.modGroup)" size="small">
                {{ getModGroupLabel(module.modGroup) }}
              </el-tag>
            </div>
          </el-col>
        </el-row>

        <el-row :gutter="24" style="margin-top: 16px;">
          <el-col :span="12">
            <div class="info-item">
              <label>文件路径</label>
              <span class="value">{{ module.path }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <label>构建标签</label>
              <span class="value">{{ module.labelPath }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 大小和统计信息 -->
      <el-row :gutter="24" style="margin-top: 24px;">
        <el-col :span="12">
          <el-card class="stats-card" shadow="never">
            <template #header>
              <div class="card-header">
                <el-icon><DataAnalysis /></el-icon>
                <span>大小信息</span>
              </div>
            </template>

            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-label">文件大小</div>
                <div class="stat-value">{{ module.human_size }}</div>
                <div class="stat-detail">{{ module.size?.toLocaleString() }} bytes</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">代码段大小</div>
                <div class="stat-value">{{ formatBytes(module.text_size) }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">数据段大小</div>
                <div class="stat-value">{{ formatBytes(module.data_size) }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">BSS段大小</div>
                <div class="stat-value">{{ formatBytes(module.bss_size) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="stats-card" shadow="never">
            <template #header>
              <div class="card-header">
                <el-icon><Connection /></el-icon>
                <span>依赖关系</span>
              </div>
            </template>

            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-label">总依赖数</div>
                <div class="stat-value">{{ module.deps_total || 0 }}</div>
                <div class="stat-detail">
                  内部: {{ module.deps_internal || 0 }} | 外部: {{ module.deps_external || 0 }}
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-label">被依赖数</div>
                <div class="stat-value">{{ module.dependedBy_total || 0 }}</div>
                <div class="stat-detail">
                  内部: {{ module.dependedBy_internal || 0 }} | 外部: {{ module.dependedBy_external || 0 }}
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-label">依赖深度</div>
                <div class="stat-value">{{ module.depth || 0 }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">提供符号</div>
                <div class="stat-value">{{ module.provided || 0 }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细信息标签页 -->
      <el-card class="detail-tabs-card" shadow="never" style="margin-top: 24px;">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="扩展信息" name="extended">
            <el-row :gutter="16">
              <el-col :span="8" v-for="(value, key) in extendedInfo" :key="key">
                <div class="extended-item">
                  <label>{{ getFieldLabel(key) }}</label>
                  <span class="value">{{ formatFieldValue(key, value) }}</span>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="依赖详情" name="dependencies">
            <el-empty v-if="!module.deps_total" description="暂无依赖关系" />
            <div v-else>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="直接依赖">
                  {{ module.deps || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="间接依赖">
                  {{ module.deps_indirect || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="内部依赖">
                  {{ module.deps_internal || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="外部依赖">
                  {{ module.deps_external || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="被依赖数">
                  {{ module.dependedBy || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="被依赖深度">
                  {{ module.dependedBy_depth || 0 }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>

          <el-tab-pane label="符号信息" name="symbols">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="提供符号数">
                {{ module.provided || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="使用符号数">
                {{ module.used || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="需要符号数">
                {{ module.needed || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="匹配符号数">
                {{ module.matched || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="重复符号数">
                {{ module.duplicated || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="未匹配符号数">
                {{ module.unmatched || 0 }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Download,
  InfoFilled,
  DataAnalysis,
  Connection
} from '@element-plus/icons-vue'
import { moduleApi } from '@/api/modules'
import { useAppStore } from '@/stores/app'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()

// 响应式数据
const loading = ref(false)
const error = ref('')
const module = ref({})
const activeTab = ref('extended')

// 计算属性
const extendedInfo = computed(() => {
  const fields = [
    'object_id', 'sa_id', 'processes', 'Pss', 'swapPss',
    'Shared_Dirty', 'Private_Dirty', 'napi', 'innerapi',
    'third_party', 'chipset', 'platformsdk', 'chipsetsdk',
    'hdiType', 'shlib_type', 'innerapi_tags', 'right_tags',
    'chipsetsdk_symbols', 'platformsdk_symbols', 'external_symbols',
    'chipsetsdk_dependedBy', 'platformsdk_dependedBy', 'unused'
  ]

  const result = {}
  fields.forEach(field => {
    if (module.value[field] !== undefined && module.value[field] !== '') {
      result[field] = module.value[field]
    }
  })

  return result
})

// 方法
const fetchModuleDetail = async () => {
  const moduleId = route.params.id
  if (!moduleId) {
    error.value = '模块ID不能为空'
    return
  }

  if (!appStore.currentProduct || !appStore.currentVersion) {
    error.value = '请先选择产品版本'
    return
  }

  loading.value = true
  error.value = ''

  try {
    const response = await moduleApi.getModuleDetail(moduleId, appStore.currentProduct, appStore.currentVersion)

    // Handle array response format from backend
    let rawData = response.data
    if (Array.isArray(rawData) && rawData.length > 0) {
      // Convert array format to object format
      // Backend format: [id, type, subsystem, component, name, modGroup, deps_total, deps_indirect, deps_self, dependedBy, ...]
      module.value = {
        id: rawData[0] || '',
        type: rawData[1] || 'unknown',
        subsystem: rawData[2] || 'unknown',
        componentName: rawData[3] || 'unknown',
        name: rawData[4] || 'Unknown Module',
        modGroup: rawData[5] || 'unknown',
        deps_total: parseInt(rawData[6]) || 0,
        deps_indirect: parseInt(rawData[7]) || 0,
        deps_self: parseInt(rawData[8]) || 0,
        dependedBy: parseInt(rawData[9]) || 0,
        dependedBy_total: parseInt(rawData[9]) || 0,
        // Add more field mappings as needed
        size: parseInt(rawData[24]) || 0,
        human_size: formatBytes(parseInt(rawData[24]) || 0),
        text_size: parseInt(rawData[25]) || 0,
        data_size: parseInt(rawData[26]) || 0,
        bss_size: parseInt(rawData[27]) || 0,
        provided: parseInt(rawData[16]) || 0,
        used: parseInt(rawData[17]) || 0,
        needed: parseInt(rawData[18]) || 0,
        matched: parseInt(rawData[19]) || 0,
        duplicated: parseInt(rawData[20]) || 0,
        unmatched: parseInt(rawData[21]) || 0,
        deps: parseInt(rawData[6]) || 0,
        deps_internal: parseInt(rawData[6]) || 0, // No separate field, using deps_total
        deps_external: 0, // No separate field for external deps
        dependedBy: parseInt(rawData[9]) || 0,
        dependedBy_depth: 0, // No separate field for depth
        dependedBy_total: parseInt(rawData[9]) || 0,
        depth: 0, // No separate field for depth
        path: rawData[35] || '',
        labelPath: rawData[36] || ''
      }
    } else {
      // Handle wrapped response format or object format
      if (rawData && typeof rawData === 'object' && Array.isArray(rawData.data)) {
        module.value = rawData.data
      } else {
        module.value = rawData || {}
      }
    }

    if (!module.value.id) {
      error.value = '未找到模块信息'
    }
  } catch (err) {
    console.error('获取模块详情失败:', err)
    if (err.response?.data?.error) {
      error.value = err.response.data.error
    } else {
      error.value = '获取模块详情失败，请重试'
    }
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.push({ name: 'Modules' })
}

const exportDetail = () => {
  // 导出功能待实现
  ElMessage.info('导出功能开发中')
}

const getModGroupTagType = (modGroup) => {
  const typeMap = {
    'kernel': 'danger',
    'driver': 'warning',
    'system': 'primary',
    'app': 'success',
    'third-party': 'info',
    'pentry': 'default'
  }
  return typeMap[modGroup] || 'default'
}

const getModGroupLabel = (modGroup) => {
  const labelMap = {
    'kernel': '内核',
    'driver': '驱动',
    'system': '系统服务',
    'app': '应用',
    'third-party': '三方库',
    'pentry': '可执行程序'
  }
  return labelMap[modGroup] || modGroup
}

const formatBytes = (bytes) => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getFieldLabel = (field) => {
  const labelMap = {
    'object_id': '对象ID',
    'sa_id': 'SA ID',
    'processes': '进程数',
    'Pss': 'PSS内存',
    'swapPss': 'Swap PSS',
    'Shared_Dirty': '共享脏页',
    'Private_Dirty': '私有脏页',
    'napi': 'NAPI支持',
    'innerapi': '内部API',
    'third_party': '第三方',
    'chipset': '芯片组',
    'platformsdk': '平台SDK',
    'chipsetsdk': '芯片组SDK',
    'hdiType': 'HDI类型',
    'shlib_type': '共享库类型',
    'innerapi_tags': '内部API标签',
    'right_tags': '权限标签',
    'chipsetsdk_symbols': '芯片组SDK符号',
    'platformsdk_symbols': '平台SDK符号',
    'external_symbols': '外部符号',
    'chipsetsdk_dependedBy': '芯片组SDK被依赖',
    'platformsdk_dependedBy': '平台SDK被依赖',
    'unused': '未使用符号'
  }
  return labelMap[field] || field
}

const formatFieldValue = (field, value) => {
  if (typeof value === 'boolean') {
    return value ? '是' : '否'
  }
  if (field.includes('size') || field.includes('Size') || field.includes('Pss')) {
    return formatBytes(value)
  }
  return value || '-'
}

// 生命周期
onMounted(() => {
  fetchModuleDetail()
})
</script>

<style lang="scss" scoped>
.module-detail {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;

    .header-content {
      .page-title {
        margin: 8px 0 0 0;
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .error-alert {
    margin-bottom: 24px;
  }

  .info-card, .stats-card, .detail-tabs-card {
    .card-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
    }
  }

  .info-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 8px;

    label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-bottom: 4px;
    }

    .value {
      font-size: 14px;
      color: var(--el-text-color-primary);
      font-weight: 500;
    }
  }

  .stats-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;

    .stat-item {
      text-align: center;
      padding: 16px;
      background: var(--el-fill-color-lighter);
      border-radius: 6px;

      .stat-label {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        margin-bottom: 8px;
      }

      .stat-value {
        font-size: 20px;
        font-weight: 600;
        color: var(--el-color-primary);
        margin-bottom: 4px;
      }

      .stat-detail {
        font-size: 11px;
        color: var(--el-text-color-secondary);
      }
    }
  }

  .extended-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 12px;
    padding: 8px;
    background: var(--el-fill-color-lighter);
    border-radius: 4px;

    label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-bottom: 4px;
    }

    .value {
      font-size: 13px;
      color: var(--el-text-color-primary);
      word-break: break-all;
    }
  }
}
</style>